from django.db import models
from django.conf import settings
from apps.common.models import BaseModel


class StreamSession(BaseModel):
    """流式会话记录表"""
    
    STATUS_CHOICES = [
        ('pending', '等待中'),
        ('streaming', '流式输出中'),
        ('completed', '已完成'),
        ('failed', '失败'),
        ('timeout', '超时'),
    ]
    
    stream_id = models.CharField(
        max_length=100,
        unique=True,
        verbose_name="流式会话UUID"
    )
    conversation = models.ForeignKey(
        'ai_chat.AIConversation',
        on_delete=models.CASCADE,
        related_name='stream_sessions',
        verbose_name="对话会话"
    )
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='stream_sessions',
        verbose_name="用户"
    )
    message = models.ForeignKey(
        'ai_chat.AIMessage',
        on_delete=models.CASCADE,
        null=True,
        blank=True,
        related_name='stream_sessions',
        verbose_name="关联消息"
    )
    status = models.CharField(
        max_length=20,
        choices=STATUS_CHOICES,
        default='pending',
        verbose_name="状态"
    )
    current_content = models.TextField(
        blank=True,
        verbose_name="当前已生成内容"
    )
    current_tokens = models.IntegerField(
        default=0,
        verbose_name="当前Token数"
    )
    estimated_tokens = models.IntegerField(
        default=0,
        verbose_name="预估总Token数"
    )
    error_message = models.TextField(
        blank=True,
        verbose_name="错误信息"
    )
    started_at = models.DateTimeField(
        null=True,
        blank=True,
        verbose_name="开始时间"
    )
    completed_at = models.DateTimeField(
        null=True,
        blank=True,
        verbose_name="完成时间"
    )
    duration_ms = models.IntegerField(
        default=0,
        verbose_name="持续时长(毫秒)"
    )
    expires_at = models.DateTimeField(
        null=True,
        blank=True,
        verbose_name="过期时间"
    )
    
    class Meta:
        verbose_name = "流式会话记录"
        verbose_name_plural = "流式会话记录"
        ordering = ['-created_at']
        indexes = [
            models.Index(fields=['stream_id']),
            models.Index(fields=['user', 'status']),
            models.Index(fields=['conversation', 'status']),
            models.Index(fields=['expires_at']),
        ]
    
    def __str__(self):
        return f"流式会话 {self.stream_id} - {self.get_status_display()}"
    
    def can_edit(self, user):
        """权限检查：是否可以编辑"""
        return self.user == user or user.is_staff
    
    def can_delete(self, user):
        """权限检查：是否可以删除"""
        return self.user == user or user.is_staff